package com.mobile.socketclient;

import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class MsgSocketClient {
    Socket socket = null;
    InputStreamReader input = null;
    InputStream in = null;
    OutputStream out = null;
    private static final String TAG = "FirstFragment";
    private AtomicInteger clientExitPoint = new AtomicInteger();

    public void socketStart() {
        try {
            socket = new Socket("127.0.0.1", 8888);
            Log.e(TAG, "客户端1启动......." );
            // 接受返回数据
            new Thread() {
                public void run() {
                    try {
                        while (true) {
                            in = socket.getInputStream();
                            ObjectInputStream ois = new ObjectInputStream(in);
                            Message msg = (Message) ois.readObject();
                            Log.e(TAG, "客户端接收到服务端返回数据：" + msg.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            out = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(out);
            String[] messageBody= {"123","456","789","hahaha","gagaga"};
            //同时不停的发送数据给服务端
            while (true) {
                int exitPoint = clientExitPoint.incrementAndGet();
                int index = new Random().nextInt(messageBody.length);
                Log.e(TAG, "index:"+index + ",发射内容是："+messageBody[index]);
                input = new InputStreamReader(new ByteArrayInputStream(messageBody[index].getBytes()));
                String msg = new BufferedReader(input).readLine();
                Message message = new Message();
                message.setId(2);
                message.setMsg(msg);
                oos.writeObject(message);
                Thread.sleep(2000);
                if (exitPoint == 5) {
                    Log.e(TAG, "关闭流了");
//                    in.close();
//                    out.close();
//                    socket.close();
                    android.os.Process.killProcess(android.os.Process.myPid());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流和连接
            try {
                in.close();
                out.close();
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

